//浅拷贝：如果普通类型没问题，但是如果是obj的话就会拷贝地址，变成改一个就改两个
function weekClone(obj) {
  return { ...obj };
}
const obj = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 213,
      f: [1, 2, 3, 4, 5, 6],
    },
  },
  d: [1, 2, 3, 4],
};

//深拷贝
const cloneArray = (array) => {
  const arr1 = [];
  array.forEach((item) => {
    arr1.push(item);
  });
  return arr1;
};
function deepclone(obj, map = new WeakMap()) {
  if (map.has(obj)) {
    return map.get(obj); // 如果对象已经被拷贝过，直接返回
  }
  const ifArray = Array.isArray(obj);
  if (ifArray) {
    const resList = cloneArray(obj);
    map[obj] = resList;
    return resList;
  }
  const newObj = {};
  map[obj] = newObj;
  Object.keys(obj).forEach((key) => {
    if (map[key]) {
      return map[key];
    } else {
      if (obj[key] && Array.isArray(obj[key] || typeof obj[key] === "object")) {
        newObj[key] = deepclone(obj[key], map);
      } else {
        newObj[key] = obj[key];
      }
    }
  });
  return newObj;
}

obj.b.d = obj;
// console.log(r1);
console.log(obj);
const r1 = deepclone(obj);
console.log("------");
console.log(r1);
console.log(obj);
